package com.jinzecloud.reportapproval.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ywm
 */
@Component
public class JwtUtil {

	private static final String SECRET_KEY = "secret";
	// 24小时
	private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 7;
	//  private static final long EXPIRATION_TIME = 30000; // 24小时

	public String generateToken(UserDetails userDetails) {
		Map<String, Object> claims = new HashMap<>();
		return Jwts.builder()
				.setClaims(claims)
				.setSubject(userDetails.getUsername())
				.setIssuedAt(new Date())
				.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
				.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
				.compact();
	}


	public boolean validateToken(String token, UserDetails userDetails) {
		String username = extractUsername(token);
		return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
	}

	public String extractUsername(String token) throws ExpiredJwtException {
		String subject;
		subject = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
		return subject;
	}

	public boolean isTokenExpired(String token) {
		Date expirationDate = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getExpiration();
		return expirationDate.before(new Date());
	}

	public static Claims extractClaims(String token) {
		return Jwts.parser()
				.setSigningKey(SECRET_KEY)
				.setAllowedClockSkewSeconds(300)
				.parseClaimsJws(token)
				.getBody();
	}
}